package com.techindata.cacheredis;

import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by wang yu on 2016/5/12.
 * redis 所有数据结构都可以使用的方法
 */
public class CacheCom {
    static Logger logger = Logger.getLogger(CacheCom.class);

    /**
     * 删除指定的key
     * @param key
     * @return
     * @throws Exception
     */
    public static long del(String key) throws Exception {
        JedisPool pool = RedisConnectionPool.getPool();
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.del(key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return -1L;
        } finally{
            RedisConnectionPool.returnResource(pool, jedis);
        }
    }

    /**
     * 对key加锁
     * @param key
     * @return
     * @throws Exception
     */
    public static long lock(String key) throws Exception {
        JedisPool pool = RedisConnectionPool.getPool();
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.setnx(key,"1");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("redis加锁失败");
        } finally{
            RedisConnectionPool.returnResource(pool, jedis);
        }
    }
    /**
     * 对key解锁
     * @param key
     * @return
     * @throws Exception
     */
    public static long unLock(String key) throws Exception {
        JedisPool pool = RedisConnectionPool.getPool();
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.del(key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("redis解锁失败");
        } finally{
            RedisConnectionPool.returnResource(pool, jedis);
        }
    }
}
